Captcha generater
import random
import string
from PIL import Image, ImageDraw, ImageFont, ImageFilter
def generate_captcha(text=None, width=200, height=70, font_size=40, output_file="captcha.png"):
# Random CAPTCHA text
if text is None:
text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
# Create blank white image
image = Image.new('RGB', (width, height), 'white')
font = ImageFont.truetype("arial.ttf", font_size) # You may need to adjust the font path
draw = ImageDraw.Draw(image)
# Draw the text at random positions
for i, char in enumerate(text):
x = 10 + i * 30 + random.randint(-5, 5)
y = 10 + random.randint(-5, 5)
draw.text((x, y), char, font=font, fill=(random.randint(0,100), 0, 0))
# Add some noise: random lines
for _ in range(5):
x1 = random.randint(0, width)
y1 = random.randint(0, height)
x2 = random.randint(0, width)
y2 = random.randint(0, height)
draw.line(((x1, y1), (x2, y2)), fill="gray", width=1)
# Apply blur to image
image = image.filter(ImageFilter.GaussianBlur(1))
# Save image
image.save(output_file)
print(f"[+] CAPTCHA saved as '{output_file}' with text: {text}")
return text
if __name__ == "__main__":
generate_captcha()
Code output
[+] CAPTCHA saved as 'captcha.png' with text: WN3C0Z